package cn.jason.service.impl;

import cn.jason.domain.Goods;
import cn.jason.lock.ItsourceLock;
import cn.jason.lock.ZookeeperDistributedLock;
import cn.jason.mapper.GoodsMapper;
import cn.jason.service.IGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @Author: Jason
 * @Date: 2022/9/19 18:53
 * zk实现分布式锁
 */
@Service
public class GoodsServiceImpl_zookeeper implements IGoodsService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public void updateNum(Map<String,Object> params) {
        //需要购买商品的ID
        Long goodsId = (Long) params.get("id");//1
        //需要购买的数量
        Integer num = (Integer) params.get("num");//2

        String resourceName = "goods_" + goodsId;//goods_1
        ItsourceLock lock = new ZookeeperDistributedLock();
        try{
            //加锁
            lock.lock(resourceName);

            //做业务
            System.out.println("线程：" + Thread.currentThread().getName()+" 拿到锁了，开始下单");
            //通过商品id获取商品  3
            Goods goods = goodsMapper.laodById(goodsId);
            if (goods.getCount()>=num){
                goodsMapper.updateNum(params);
                System.out.println("线程：" + Thread.currentThread().getName()+" 下单成功，购买数量：" + num);
            }else{
                System.out.println("线程：" + Thread.currentThread().getName()+" 拿到锁了，但库存不足，下单失败");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            if (lock != null) {
                //释放锁
                lock.unlock(resourceName);
            }
        }
    }

    @Override
    public Goods getById(Long id) {
        return goodsMapper.laodById(1L);
    }
}
